package hu.veilingsite.server;

import hu.veilingsite.client.Service;
import hu.veilingsite.shared.Auction;
import hu.veilingsite.shared.Bid;
import hu.veilingsite.shared.Category;
import hu.veilingsite.shared.ClientUser;
import hu.veilingsite.shared.FieldVerifier;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ServiceImpl extends RemoteServiceServlet implements Service {
	Core c = new Core();

	public boolean login(String user, String pass) {
		return c.loginUser(user, pass);
	}
	
	public ArrayList<Auction> getLatestAcutions(){
		return c.db.getLatestAuctions();
	}

	public boolean registreer(String name, String password, String email, String address, String residence, int birthdateday, int birthdatemonth, int birthdateyear){
		Date birthdate = new Date(birthdateyear - 1900, birthdatemonth - 1, birthdateday);
		User newUser = new User(name, address, residence, birthdate, true, true, false, 0, password, email);
		if(newUser == null) {
			return false;
		} else{
			return c.db.insertUser(newUser);
		}
	}
	
	public ClientUser getUser(String email){
		User me = c.db.getUser(email);
		return new ClientUser(me.getId(),me.getName(), me.getAddress(),me.getResidence(),me.getBirthDate(), me.isMaybid(), me.isMayoffer(),me.isIsadmin(),me.getCredits(), me.getEmail());
	}

	public boolean updatePassword(String password,String email) {
		User user = c.db.getUser(email);
		user.setPassword(password);
		return c.db.saveUser(user);
	}
	
	public boolean updateUser(ClientUser user) {
		System.out.println("user updating 1");
		User dbUser = new User();
		dbUser.fromClientUser(user);
		boolean rs = c.db.saveUser(dbUser);
		System.out.println(dbUser.toString());
		System.out.println("user updating 2");
		if (rs) {
			System.out.println("gelukt");
			return true;
		} else {
			System.out.println("niet gelukt");
			return false;
		}
	}
	
	public ArrayList<ClientUser> getUsers(){
		ArrayList<User> users = c.db.getUsers();
		ArrayList<ClientUser> give = new ArrayList<ClientUser>();
		for( User u : users ){
			give.add(u.makeClient());
		}
		return give;
	}

	public ArrayList<Auction> getAllAuctions() {
		return c.db.getAuctions();
	}

	public ArrayList<Auction> getAllAuctionsFromUser(int id) {
		return c.db.getAuctionsFromUser(id);
	}

	public boolean createAuction(int ai, int ci, String tt, String dp,
			int sp, java.util.Date ed, int vs) {
		java.sql.Date sqlDate = FieldVerifier.convertUtilDateToSqlDate(ed);
		return c.db.insertAuction(new Auction(0, ai, ci, tt, dp, sp, sqlDate, vs));
	}

	public boolean updateCategory(Category cat) {
		System.out.println("Saving "+cat.getTitle());
		return c.db.saveCategory(cat);
	}

	public ArrayList<Category> getCategories() {
		return c.db.getCategorys();
	}

	public boolean insertCategory(Category cat) {
		return c.db.insertCategory(cat);
	}

	public boolean deleteCategory(int id) {
		return c.db.deleteCategory(id);
	}

	public Auction getAuction(int id) {
		return c.db.getAuction(id);
	}

	public boolean createBieding(int userID, int auctionID, int offer,
			java.util.Date date) {
		java.sql.Date sqlDate = FieldVerifier.convertUtilDateToSqlDate(date);
		return c.db.insertBid(new Bid(0, userID, auctionID, offer, sqlDate));
	}

	public Bid getHighestBid(String string, int year,int month,int week,int day) {
		Bid bid = c.db.getHighestBid(string,year,month,week,day);
		return bid;
	}

	public ArrayList<Integer> getYears() {
		return c.db.getYears();
	}
	
	public int valCoupon(String coup, ClientUser cu){
		int i = c.db.getAantal(coup);
		if(i != 0){
			User u = new User();
			u.fromClientUser(cu);
			u.depostCredits(i);
			c.db.saveUser(u);
			c.db.verwijderCoupon(coup);
		}
		return i;
	}
	
	public void deleteAuction(int id){
		c.db.deleteAuction(id);
	}

	@Override
	public Category getCategory(int id) {
		return c.db.getCategory(id);
	}

	@Override
	public ArrayList<Auction> getBestBidAuctions() {
		return c.db.getBestBidAuctions();
	}
	
	public ArrayList<Auction> getAuctionAdmin(){
		ArrayList<Auction> lijst = c.db.getAuctionsAdmin();
		return lijst;
	}

	public ArrayList<Bid> getBidsFromAuction(int auctionID) {
		return c.db.getBidsFromAuction(auctionID);
	}

	public ArrayList<Bid> getBidsFromUser(int id) {
		return c.db.getBidsFromUser(id);
	}

	public String getNameOfUser(int userId) {
		return c.db.getNameOfUser(userId);
	}
	
	public void saveAuction(Auction veiling){
		c.db.saveAuction(veiling);
	}

	public boolean deleteBid(int bidId) {
		return c.db.deleteBid(bidId);
	}

	public ClientUser getUser(int userId) {
		User usr = c.db.getUser(userId);
		return usr.makeClient();
	}

	public boolean acceptBid(int bidId) throws Exception {
		Bid bid = c.db.getBid(bidId);
		int bidCredits = bid.getCredits();
		if(bid != null){
			Auction auction = c.db.getAuction(bid.getAuction_id());
			User bieder = c.db.getUser(bid.getUser_id());
			if (auction != null && bieder != null) {
				User aanbieder = c.db.getUser(auction.getAuthor_id());
				if (aanbieder != null) {
					if (bieder.getCredits()-bidCredits >= 0) {
						aanbieder.depostCredits(bidCredits);
						if (c.db.saveUser(aanbieder)){
							if (bieder.withdrawCredits(bidCredits)){
								if (c.db.saveUser(bieder)){
									c.db.deleteAuction(auction.getId());
									return true;
								}
							}
						}
					} else {
						String msg = "Bieder heeft te weinig credits om te betalen.";
						if (c.db.deleteBid(bidId)) {
							msg += "\nDeze bieding is verwijderd.";
						}
						throw new Exception(msg);
					}
				}
			}
		}
		return false;
	}
}